//
//  UIImage.swift
//  vgbox
//
//  Created by 宋海胜 on 2019/6/25.
//  Copyright © 2019 Swift Xcode. All rights reserved.
//

import Foundation
import Kingfisher
import Toast_Swift

extension UIImage {
    
    // MARK: - 重新size
    /// 重新size
    ///
    /// 缩放图片，将大图片缩放到新的size不会变形。
    /// 如果图片本身尺寸比新图片尺寸要小，填充白色像素
    /// 缩放时，先按照比例系数，将图片整体缩放到比需要缩放的图片的小边大的图片。
    /// 然后从图片中心进行裁剪图片。
    func resize(newSize: CGSize) -> UIImage {
        
        let newWidth = newSize.width        //新的宽
        let newHeight = newSize.height      //新的高
        
        //TODO: 先缩放，按照比例缩放到大边
        ///获取大边
        let scaledBigWidth = newWidth > newHeight ? newWidth : newHeight
        
        ///本身的小边
        let selfSmallLength = size.width < size.height ? size.width : size.height
        
        //如果图片宽高不同，需要在缩放时考虑到宽高比例
        //保证比例不拉伸
        
        let scale = scaledBigWidth / selfSmallLength
        
        //等比缩放的size
        let scaleSize = CGSize(width: self.size.width * scale, height: self.size.height * scale)
        
        
        //TODO: 先整体缩放到大边
        let scaledImage = self.scaleFromImage(toSize: scaleSize)    //等比缩放的image
        
        //TODO: 从大图片中绘出图片
        let scaledRect = CGRect(x: (scaleSize.width - newSize.width)*0.5, y: (scaleSize.height - newSize.height)*0.5, width: newSize.width, height: newSize.height)
        
        let subImage = scaledImage.getSubImage(size: scaledRect)
        return subImage
    }
    
    
    // MARK: - scale
    /// uiimage缩放
    func scaleFromImage (toSize size: CGSize) -> UIImage{
        
        UIGraphicsBeginImageContext(size)
        self.draw(in: CGRect(x:0, y:0, width:size.width,height:size.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
    
    
    
    /// 从图片中去取图片
    func getSubImage (size: CGRect) -> UIImage {
        
        let subImageRef: CGImage = self.cgImage!.cropping(to: size)!
        let smaillBounds = CGRect(x:0, y:0, width:CGFloat(subImageRef.width),height:CGFloat(subImageRef.height))
        UIGraphicsBeginImageContext(smaillBounds.size)
        _ = UIGraphicsGetCurrentContext()
        
        //        CGContextDrawImage(context,smaillImage,subImageRef)
        let smaillImage = UIImage(cgImage: subImageRef)
        UIGraphicsEndImageContext()
        return smaillImage
    }
    
    
    /// 先缩放后裁剪
    func scaleAndCrop(size: CGSize) -> UIImage {
        //计算大边
        _ = size.width > size.height ? size.width : size.height
        
        //计算小边
        let min = size.width < size.height ? size.width : size.height
        
        //计算裁剪用的y
        let point = abs(size.width - size.height)/2
        
        //判断宽高那一个大
        let isY = size.width > size.height
        
        UIGraphicsBeginImageContext(self.size)
        self.draw(in: CGRect(x:0, y:0, width:min, height:min))
        
        //获取到正方形，以大边为准
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        //从新图片中剪切
        //DEBUGMODE.DEBUGPRINT("newImage size \(newImage.size)")
        
        let smailBounds: CGRect!
        
        if isY {
            smailBounds = CGRect(x:0, y:point, width:size.width,height:size.height)
        } else {
            smailBounds = CGRect(x:point, y:0, width:size.width,height:size.height)
        }
        
        let subImageRef: CGImage = newImage!.cgImage!.cropping(to: smailBounds)!
        
        UIGraphicsBeginImageContext(smailBounds.size)
        _ = UIGraphicsGetCurrentContext()
        //        CGContextDrawImage(context, smailBounds, subImageRef)
        let smaillImage = UIImage(cgImage: subImageRef)
        
        UIGraphicsEndImageContext()
        
        //DEBUGMODE.DEBUGPRINT("smaillImage size \(smaillImage.size)")
        return smaillImage
    }
    
    
    /// 取中间像素
    func getCenterCrop(newSize: CGSize) -> UIImage {
        
        var scaleW: CGFloat = 1
        var scaleH: CGFloat = 1
        
        if self.size.width < newSize.width {
            //宽小
            scaleW = newSize.width/self.size.width
        }
        
        if self.size.height < newSize.height {
            //高小
            scaleH = newSize.height/self.size.height
        }
        
        let maxScale = scaleW > scaleH ? scaleW : scaleH
        
        UIGraphicsBeginImageContext(newSize)
        
        self.draw(in: CGRect(x:0,y: 0,width:self.size.width*maxScale,height:self.size.height*maxScale))
        
        let needImg = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return needImg!
    }
    
    
    /// 先缩放后裁剪
    func getScaleCenterCrop(newSize: CGSize) -> UIImage {
        
        var scaleW: CGFloat = 1
        var scaleH: CGFloat = 1
        
        if self.size.width < newSize.width {
            //宽小
            scaleW = newSize.width/self.size.width
        }
        
        if self.size.height < newSize.height {
            //高小
            scaleH = newSize.height/self.size.height
        }
        
        //缩放系数
        let maxScale = scaleW > scaleH ? scaleW : scaleH
        
        UIGraphicsBeginImageContext(self.size)
        
        self.draw(in: CGRect(x:0, y:0, width:self.size.width*maxScale, height:self.size.height*maxScale))
        
        let result = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return result!
    }
    
    /// 按照宽度截取
    func scaleImageWithWidth(defineWidth: CGFloat) -> UIImage {
        
        if defineWidth >= self.size.width {
            return self
        }
        //缩放
        let currentScale = defineWidth / self.size.width
        let scaledRect = CGRect(x:0, y:0, width:defineWidth, height:self.size.height * currentScale)
        let scaledSize = CGSize(width:defineWidth, height:self.size.height * currentScale)
        UIGraphicsBeginImageContext(CGSize(width:floor(scaledSize.width),height:floor(scaledSize.height)))
        self.draw(in: scaledRect)
        let newImg = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImg!
    }
    
    ///按照高度截取
    
    
    /// Image保存
    func vg_saveImageToAlumb(view: UIView) {
        UIImageWriteToSavedPhotosAlbum(self, self, #selector(result(view:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    /// Image回调
    @objc func result(view: UIView, didFinishSavingWithError: NSError?, contextInfo: AnyObject) {
        
        if (didFinishSavingWithError != nil) {
            view.makeToast("图片保存失败", duration: 1.0)
        } else {
            view.makeToast("图片已保存至相册", duration: 1.0)
        }
    }
    
    /// 根据url获取图片尺寸size
    static func getImageSize(_ url: String?) -> CGSize {
        
        guard let urlStr = url, url != "" else {
            return CGSize.zero
        }
        let tempUrl = URL(string: urlStr)
        let imageSourceRef = CGImageSourceCreateWithURL(tempUrl! as CFURL, nil)
        var width: CGFloat = 0
        var height: CGFloat = 0
        if let imageSRef = imageSourceRef {
            let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSRef, 0, nil)
            if let imageP = imageProperties {
                let imageDict = imageP as Dictionary
                width = imageDict[kCGImagePropertyPixelWidth] as! CGFloat
                height = imageDict[kCGImagePropertyPixelHeight] as! CGFloat
            }
        }
        return CGSize(width: width, height: height)
    }
    
    func drawTextInImage(text: String) -> UIImage {
        //开启图片上下文
        UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
        //图形重绘
        self.draw(in: CGRect.init(x: 0, y: (44 + STATUSBAR_HEIGHT), width: self.size.width, height: self.size.height))
        //水印文字属性
        let att = [NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font: UIFont.systemFont(ofSize: Constant.font_1), NSAttributedString.Key.backgroundColor: UIColor.white]
        //水印文字大小
        let size =  text.size(withAttributes: att)
        let drawwidth : CGFloat = self.size.width - 24
        var from : Int = 0
        //绘制文字
        if size.width > drawwidth {
            
            var AllIndex : Int = 20
            var subtext = text.subString(to: AllIndex)
            var subsize =  subtext.size(withAttributes: att)
            var alltext : String = text.subString(to: AllIndex)
            var allsize : CGSize = alltext.size(withAttributes: att)
            var textArr : [String] = []
            
            while size.width > allsize.width {
                while drawwidth > subsize.width {
                    AllIndex = AllIndex + 1
                    if let range = Range.init(NSMakeRange(from, AllIndex-from), in: text) {
                        
                        subtext = text.substring(with: range)
                        subsize = subtext.size(withAttributes: att)
                        
                        //第一行的subindex和subtext
                        //当其为最后一行时无法成立
                        if text.length == AllIndex {
                            break
                        }
                    } else {
                        break
                    }
                }
                subsize = "subtext".size(withAttributes: att)
                textArr.append(subtext)
                from = AllIndex//第二行的头
                alltext = text.subString(to: AllIndex)
                allsize = alltext.size(withAttributes: att)
            }
            
            for i in 0...textArr.count-1 {
                let mytext = textArr[i]
                mytext.draw(in: CGRect.init(x: 12, y: 12 + (44 + STATUSBAR_HEIGHT)+size.height*CGFloat(i+1), width: drawwidth, height: size.height), withAttributes: att)
            }
        } else {
            text.draw(in: CGRect.init(x: 12, y: 12 + (44 + STATUSBAR_HEIGHT), width: self.size.width-24, height: size.height), withAttributes: att)
        }
        
        //从当前上下文获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        return image!
    }
    
    func rescaleImageToSize(size: CGSize) -> UIImage {
        let rect = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(rect.size)
        self.draw(in: rect)
        let resImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return resImage
        
    }
}

extension UIImageView {
    
    /// 从缓存取image
    static func setImageFromCache(imgV: UIImageView, imageUrl: String) {

        DispatchQueue.main.async {
//            if let memoryImage = SDImageCache.shared().imageFromMemoryCache(forKey: imageUrl) {
//                let img = memoryImage
//                DispatchQueue.main.async(execute: {
//                    imgV.image = img
//
//                })
//            } else {
//                SDWebImageUtils.sharedInstance.downloadImage(url: URL.init(string: imageUrl), options: .refreshCached, progress: nil, completed: { (image, data, error, type, finish, url) in
//                    DispatchQueue.main.async {
//                        if let _ = image {
//
//                        }
//                    }
//                })
//            }
        }
    }
    
    func vg_setImageViewWithUrlStr(_ urlStr: String, _ placeHolder : String) {
//        self.kf.setImage(with: <#T##Resource?#>, placeholder: <#T##Placeholder?#>, options: <#T##KingfisherOptionsInfo?#>, progressBlock: <#T##DownloadProgressBlock?##DownloadProgressBlock?##(Int64, Int64) -> Void#>, completionHandler: <#T##CompletionHandler?##CompletionHandler?##(Image?, NSError?, CacheType, URL?) -> Void#>)
        
        let url = URL(fileURLWithPath: urlStr)
        
        self.kf.setImage(with: url)
    }
    
    func sy_name(_ imgName: String) {
        self.image = UIImage(named: imgName)
    }
    
    func sy_setWithUrl(_ urlStr: String?, _ placeHolder : String? = nil) {
//        self.kf.setImage(with: <#T##Resource?#>, placeholder: <#T##Placeholder?#>, options: <#T##KingfisherOptionsInfo?#>, progressBlock: <#T##DownloadProgressBlock?##DownloadProgressBlock?##(Int64, Int64) -> Void#>, completionHandler: <#T##CompletionHandler?##CompletionHandler?##(Image?, NSError?, CacheType, URL?) -> Void#>)
        
        let url = URL(string: IMGIP + (urlStr ?? ""))
        
        self.kf.setImage(with: url, placeholder: UIImage(named: placeHolder ?? ""), options: .none) { (a, b) in
            
        } completionHandler: { (res) in
            
        }

    }
}
